<?php
/**
 * 归属地
 * Class BelongingToLocal
 * @package app\common\util
 */
class BelongingToLocal
{
    protected $cityArr = ["北京", "上海", "天津", "重庆"];

    protected $cityStr = "北京,上海,天津,重庆,河北,山西,河南,辽宁,吉林,黑龙江,内蒙古,江苏,山东,安徽,浙江,福建,湖北,湖南,广东,广西,江西,四川,海南,贵州,云南,西藏,陕西,甘肃,青海,宁夏,新疆,港澳台";

    /**
     * 通过手机号获取归属
     * @param string $tel
     * @return array
     */
    public function useTel($tel = '')
    {
        list($area, $city) = $this->tel_360($tel);
        if ($area == '' || $city == '') list($area, $city) = $this->tel_K780($tel);
        if ($area == '' || $city == '') list($area, $city) = $this->tel_51240($tel);
        if ($area == '' || $city == '') list($area, $city) = $this->tel_sg($tel);
        return $this->format($area, $city);
    }

    /**
     * 通过ip获取归属
     * @param string $ip
     * @return array
     */
    public function useIp($ip = '')
    {
        list($area, $city) = $this->ip_360($ip);
        if ($area == '' || $city == '') list($area, $city) = $this->ip_bd($ip);
        if ($area == '' || $city == '') list($area, $city) = $this->ip_ip($ip);
        return $this->format($area, $city);
    }

    /**
     * 360
     * @param $ip
     * @return array
     */
    protected function ip_360($ip)
    {
        $this->header = [];
        $result = $this->request("http://www.ip360.cn/", "ip={$ip}&action=2");
        $area = $city = $result_str = '';
        $location = $this->getSubstr($result, 'IP详细地址：&nbsp; <font color=#cc3300>', '</font>');
        $arrConf = explode(",", $this->cityStr);
        $isHas = false;
        foreach ($arrConf as $value) {
            if ($isHas) break;
            $area = $value;
            if ($value != '' && strpos(mb_substr($location, 0, 6), $value) !== false) $isHas = true;
            if (!empty($c = $this->getSubstr($location, $value . '自治区', '市'))) $city = $c;
            if (!empty($c = $this->getSubstr($location, $value . '省', '市'))) $city = $c;
            if (!empty($c = $this->getSubstr($location, $value . '市', '市'))) $city = $c;
        }
        list($area, $city) = $this->filter($area, $city, $result_str);
        return [$area, $city];
    }

    /**
     * 360
     * @param $tel
     * @return array
     */
    protected function tel_360($tel)
    {
        $this->header = [];
        $result = $this->request("https://cx.shouji.360.cn/phonearea.php?number={$tel}");
        $result = json_decode($result, true);
        $area = $city = $result_str = '';
        $area = $result['data']['province'];
        $city = $result['data']['city'];
        list($area, $city) = $this->filter($area, $city, $result_str);
        return [$area, $city];
    }

    /**
     * api.k780.com
     * @param $tel
     * @return array
     */
    protected function tel_K780($tel)
    {

        $this->header = [];
        $result = $this->request("http://api.k780.com/?app=phone.get&phone={$tel}&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json");
        $result = json_decode($result, true);
        $area = $city = $result_str = '';
        $result_str = $result['result']['att'];
        $result = explode(',', $result['result']['att']);
        $area = $result[1];
        $city = $result[2];
        list($area, $city) = $this->filter($area, $city, $result_str);
        return [$area, $city];
    }

    /**
     * 便民
     * @param $tel
     * @return array
     */
    protected function tel_51240($tel)
    {
        $this->header = [];
        $result = $this->request("http://shouji.51240.com/{$tel}__shouji/");
        $regex = '/<td bgcolor=\"#FFFFFF\" align=\"center\" style=\"font-size:16px;\">(.*)<\/td>/';
        preg_match_all($regex, $result, $result);
        $area = $city = $result_str = '';
        if (isset($result[1]) && isset($result[1][1])) {
            $result_str = $result = $result[1][1];
            $result = explode(" ", $result);
            if (isset($result[0]) && isset($result[1])) {
                $area = $result[0];
                $city = $result[1];
            }
        }
        list($area, $city) = $this->filter($area, $city, $result_str);
        return [$area, $city];
    }

    /**
     * 搜狗
     * @param $tel
     * @return array
     */
    protected function tel_sg($tel)
    {
        $this->header = [];
        $result = $this->request("https://www.sogou.com/websearch/phoneAddress.jsp?phoneNumber={$tel}");
        $result = mb_convert_encoding($result,  'utf-8', 'gbk');
        $regex='/void\(\"(.*)\"\)/';
        preg_match_all($regex,$result,$result);
        $area = $city = $result_str = '';
        if(isset($result[1]) && isset($result[1][0])) {
            $result_str = $result = $result[1][0];
            $result = explode(" ",$result);
            $arrConf = explode(",", $this->cityStr);
            foreach ($arrConf as $value) {
                if ($value != '' && strpos($result[0], $value) !== false) {
                    $area = $value;
                    $city = $result[0];
                    $city = str_replace("省", "", $city);
                    $city = str_replace($area, "", $city);
                    break;
                }
            }
        }
        list($area, $city) = $this->filter($area, $city, $result_str);
        return [$area, $city];
    }

    /**
     * www.ip.cn
     * @param $ip
     * @return array
     */
    protected function ip_ip($ip)
    {
        $this->header = [
            "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36",
            "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
            "Host: www.ip.cn"
        ];
        $result = $this->request("https://www.ip.cn/api/index?ip={$ip}&type=1");
        $regex='/address\":\"中国  (.*)\",\"ip\"/';
        preg_match_all($regex,$result,$result);
        $area = $city = $result_str = '';
        if(isset($result[1]) && isset($result[1][0])) {
            $result_str = $result = $result[1][0];
            $result = explode(" ",$result);
            if (isset($result[0]) && isset($result[1])) {
                $area = $result[0];
                $city = $result[1];
            }
        }
        list($area, $city) = $this->filter($area, $city, $result_str);
        return [$area, $city];
    }

    /**
     * 百度
     * @param $ip
     * @return array
     */
    protected function ip_bd($ip)
    {
        $this->header = ['Host: sp0.baidu.com'];
        $result = $this->request('http://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=' . $ip . '&co=&resource_id=6006&oe=utf8');
        $data = json_decode($result, true);
        $area = $city = $result_str = '';
        if (!empty($data['data'])) {
            $location = $data['data'][0]['location'];
            $arrConf = explode(",", $this->cityStr);
            $isHas = false;
            foreach ($arrConf as $value) {
                if ($isHas) break;
                $area = $value;
                if ($value != '' && strpos($location, $value) !== false) $isHas = true;
                if (!empty($c = $this->getSubstr($location, '自治区', ' '))) $city = $c;
                if (!empty($c = $this->getSubstr($c, '市', ' '))) $city = $c;
                if (!empty($c = $this->getSubstr($c, '省', ' '))) $city = $c;
            }
        }
        list($area, $city) = $this->filter($area, $city, $result_str);
        return [$area, $city];
    }

    /**
     * 过滤字符
     * @param $area
     * @param $city
     * @param $str
     * @return array
     */
    protected function filter($area, $city, $str)
    {
        $area = str_replace('省', '', $area);
        $city = str_replace('市', '', $city);
        $city = str_replace('省', '', $city);
        if (strpos($str, '香港') !== false) {
            $area = '港澳台';
            $city = '香港';
        } else if (strpos($str, '澳门') !== false) {
            $area = '港澳台';
            $city = '澳门';
        } else if (strpos($str, '台湾') !== false) {
            $area = '港澳台';
            $city = '台湾';
        }
        $index = array_search($area, $this->cityArr);
        if ($index !== false) $city = $this->cityArr[$index];
        return [$area, $city];
    }

    /**
     * 格式化
     * @param $area
     * @param $city
     * @return array
     */
    protected function format($area, $city)
    {
        $arrConf = explode(",", $this->cityStr);
        $isHas = false;
        foreach ($arrConf as $value) {
            if ($value != '' && strpos($area, $value) !== false) {
                $isHas = true;
                $area = $value;
            }
        }
        if (!$isHas) {
            unset($city);
            unset($area);
        }
        if (isset($area) && isset($city) && !empty($area) && !empty($city)) {
            return ['res' => true, 'country' => '中国', 'area' => $area, 'city' => $city];
        } else {
            return ['res' => false];
        }
    }


    /**
     * 文本取中间
     * @param $str
     * @param $leftStr
     * @param $rightStr
     * @return bool|string
     */
    protected function getSubstr($str, $leftStr, $rightStr)
    {
        $left = strpos($str, $leftStr);
        $right = strpos($str, $rightStr, $left);
        if ($left < 0 or $right < $left) return '';
        return substr($str, $left + strlen($leftStr), $right - $left - strlen($leftStr));
    }

    protected $remoteAddress;
    protected $header = [];
    protected function request($url, $post = null, $cookie = '', $returnCookie = 0)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        if ($this->remoteAddress) {
            curl_setopt($curl, CURLOPT_PROXY, $this->remoteAddress);
        }
        //curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if ($post !== null) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
        }
        if ($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return curl_error($curl);
        }
        curl_close($curl);
        if ($returnCookie) {
            list($header, $body) = explode("\r\n\r\n", $data);
            preg_match_all("/set\-cookie:([^\r\n]*)/i", $header, $matches);
            $cookie = [];
            foreach ($matches[1] as $item) {
                $cookie[] = explode(';', $item)[0];
            }
            return ['body' => $body, 'header' => $header, 'cookie' => $cookie];
        }
        return $data;
    }
}
